package com.zodiac.app.datathinking.szse;

import com.github.lzm320a99981e.quickly.starter.SpringContextHelper;
import com.zodiac.app.datathinking.configuration.CustomizeApplicationProperties;
import org.springframework.retry.annotation.Recover;

import java.util.HashMap;
import java.util.Map;

/**
 * 抽取器公共信息
 *
 * @param <I>
 * @param <O>
 */
public abstract class AbstractExtractor<I, O> implements Extractor<I, O> {
    private String apiCode;

    public AbstractExtractor() {
        this.apiCode = getClass().getSimpleName().replace(Extractor.class.getSimpleName(), "");
    }

    public String getApiCode() {
        return apiCode;
    }

    private CustomizeApplicationProperties.Szse.ApiConfig getApiConfig() {
        return SpringContextHelper.getBean(CustomizeApplicationProperties.class).getSzse().getApis().get(this.apiCode);
    }

    protected String getApiUrl() {
        String apiUrl = String.valueOf(getApiConfig().getUrl());
        Map<String, Object> commonParams = new HashMap<>();
        commonParams.put("random", Math.random());
        for (Map.Entry<String, Object> entry : commonParams.entrySet()) {
            apiUrl = apiUrl.replace("{" + entry.getKey() + "}", entry.getValue().toString());
        }
        return apiUrl;
    }

    protected String parseApiUrl(Map<String, Object> params) {
        String apiUrl = getApiUrl();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            apiUrl = apiUrl.replace("{" + entry.getKey() + "}", entry.getValue().toString());
        }
        return apiUrl;
    }

    @Recover
    protected O recover(Exception e) {
        Context.getCurrentContext().setTermination(true);
        Context.getCurrentContext().setExtractRecoverExceptionStackTrace(e);
        return null;
    }
}
